<template>
  <div class="bgc-default pad-20">
    <div class="bg-color-white pad-20">
      <div class="tabs-box mar-t--10">
        <el-tabs v-model="order.orderStatus" @tab-click="orderStatusClick">
          <el-tab-pane :label="labels[1]" name="1"> </el-tab-pane>
          <el-tab-pane :label="labels[20]" name="20"> </el-tab-pane>
          <el-tab-pane :label="labels[2]" name="2"> </el-tab-pane>
          <el-tab-pane :label="labels[3]" name="3"> </el-tab-pane>
          <el-tab-pane :label="labels[0]" name="0"> </el-tab-pane>
          <el-tab-pane :label="labels[4]" name="4"> </el-tab-pane>
          <el-tab-pane :label="labels[5]" name="5"> </el-tab-pane>
          <el-tab-pane :label="labels[100]" name="100"></el-tab-pane>
        </el-tabs>
      </div>
      <!--顶部搜索 -->
      <div id="topSearch" class="top-operate-default flex-col"
        style="align-items: baseline; padding: 20px 0; height: 100%; ">
        <div class="search-item">
          <label>搜索订单：</label>
          <el-select v-model="order.textCol">
            <el-option label="订单号" value="orderNo"></el-option>
            <el-option label="来源订单号" value="sellApartOrderNo"></el-option>
            <el-option label="来源企业" value="supplyAllianceEnterpriseName"></el-option>
            <el-option label="收货人" value="customerNickname"></el-option>
            <el-option label="收货人电话" value="customerPhone"></el-option>
            <el-option label="商品名称" value="goodsTitle"></el-option>
          </el-select>
          <el-input style="width: 200px;" v-model="order.textValue" placeholder="请输入内容"></el-input>
          <label class="mar-l-20">时间筛选：</label>
          <el-select class="pad-l-10" v-model="order.timeCol">
            <el-option label="下单时间" value="createTime"></el-option>
            <el-option label="付款时间" value="payTime"></el-option>
            <el-option label="发货时间" value="deliveryTime"></el-option>
            <el-option label="收货时间" value="receivedTime"></el-option>
            <el-option label="完成时间" value="completeTime"></el-option>
          </el-select>
          <el-date-picker v-model="order.timeValue" type="daterange" range-separator="至"
            value-format="yyyy-MM-dd HH:mm:ss" :default-time="['00:00:00', '23:59:59']" start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>

          <el-select v-model="order.apartOrderSource" placeholder="订单发货方" clearable class="mar-l-10 cus-select">
            <el-option label="全部订单发货方" value=""></el-option>
            <el-option label="企业发货" value="10"></el-option>
            <el-option label="供应商发货" value="20"></el-option>
            <el-option label="供货联盟" value="40"></el-option>
          </el-select>
        </div>
        <div class="search-item mar-t-10"> 
          <label>订单来源：</label>
          <el-select v-model="order.isSupplyAllianceOrder" placeholder="订单来源" class="mar-l-10 cus-select" clearable>
            <el-option label="全部" value=""></el-option>
            <el-option label="企业订单" value="0"></el-option>
            <el-option label="供货联盟订单" value="1"></el-option>
          </el-select>
          <el-button-group class="mar-l-20">
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-button-group>
        </div>
      </div>
      <!-- 全选、操作 -->
      <div>
        <div class="pad-t-15 pad-b-15 font-14 v-align-c">
          <el-checkbox class="mar-l-14 mar-r-0" v-model="allChecked" @change="selectAll"><span
              class="mar-l-20">当页全选</span></el-checkbox>
          <span class="pad-l-4 pad-r-4">|</span>
          <div class="width-80">已选{{multipleSelection.length}}项</div>
          <el-button class="batch-btn" @click="exportOrder">批量导出</el-button>
          <template v-if="!warehouseDeliverFlag">
            <el-button v-if="order.orderStatus == 1 || order.orderStatus == 20" @click="doBatchGenerateSend">批量生成发货单</el-button>
          </template>
        </div>
      </div>
      <!-- 内容列表 -->
      <div class="table-container">
        <el-table ref="multipleTable" :data="orderList" @selection-change="handleSelectionChange" v-loading="listLoading" element-loading-text="加载中">
          <el-table-column width="50px" type="selection"></el-table-column>
          <el-table-column width="280px" label="订单信息" fixed="left">
            <template slot-scope="scope">
              <div class="flex v-align-c cursor-p" @click="showDetail(scope.row)">
                <label v-if="scope.row.goodsImageUrl"><img :src="scope.row.goodsImageUrl"
                    class="t-goods-pic cursor-p"></label>
                <div class="font-14 pad-l-10  v-align-h height-65">
                  <div class="goods-title">
                    <div class="line-2">{{scope.row.goodsTitle}}</div>
                  </div>
                  <span class="font-color-6 font-10 pad-3 mar-t-5" style="border: 1px solid #ccc;border-radius: 4px;"
                    v-if="scope.row.payType !== null && scope.row.payType > 0">
                    <span v-if="scope.row.payType === 5">
                      <el-image src="../../../../../static/images/wallet.png"
                        style="width: 12px;height: 12px;vertical-align:inherit;">
                      </el-image><span class="mar-l-5">线下支付</span>
                    </span>
                    <span v-else-if="scope.row.payType === 1">
                      <el-image src="../../../../../static/images/wechat.png"
                        style="width: 12px;height: 12px;vertical-align:inherit;">
                      </el-image><span class="mar-l-5">微信支付</span>
                    </span>
                  </span>
                  <!-- <div v-if="scope.row.goodsTitle.length <= 20">{{scope.row.goodsTitle}}</div>
                  <div v-if="scope.row.goodsTitle.length > 20">{{scope.row.goodsTitle.slice(0,20) + '...'}}</div> -->

                </div>

                <!-- <p style="border: 0.5px solid; border-radius: 4px;border-color: #CCCCCC;">
                  <el-image src="../../../../../static/images/wallet.png" style="width: 15px;height: 15px;">
                  </el-image><span>线下支付</span>
                  <img src="../../../../../static/images/wallet.png" />
                    <img src="../../../../../static/images/wechat.png" />微信支付
                </p> -->
              </div>
            </template>
          </el-table-column>
      
          <el-table-column width="210px" label="订单号" align="center" prop="orderNo">
            <template slot-scope="scope">
              <span>{{scope.row.orderNo}}</span>
              <div v-if="scope.row.sellApartOrderId != null">
                来源：{{scope.row.sellApartOrderNo}}
              </div>
            </template>
          </el-table-column>

          <el-table-column width="200px" label="订单来源" align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.sellApartOrderId != null">
                <span>供货联盟订单</span>
                <div>{{scope.row.supplyAllianceEnterpriseName}}</div>
              </span>
              <span v-else>企业订单</span>
            </template>
          </el-table-column>

          <el-table-column width="180px" label="收货人" align="center">
            <template slot-scope="scope">
              <div v-if="scope.row.customerNickname">
                <div>{{scope.row.customerNickname}}</div>
                <div v-if="scope.row.customerPhone">{{scope.row.customerPhone}}</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column width="80px" label="售后状态" align="center">
            <template slot-scope="scope">
              <div>
                <template v-if="scope.row.afterSaleFlag == 0">
                  <span class="font-color">{{dict.afterSaleFlag[scope.row.afterSaleFlag]}}</span>
                </template>
                <template v-else>
                  <span v-if="scope.row.orderNo" class="font-red cursor-p" @click="doLinkAfter(scope.row)">{{dict.afterSaleFlag[scope.row.afterSaleFlag]}}</span>
                  <span v-else class="font-red">{{dict.afterSaleFlag[scope.row.afterSaleFlag]}}</span>
                </template>
              </div>
            </template>
          </el-table-column>
          <el-table-column v-if="false" width="150px" label="零售价">
            <template slot-scope="scope">
              <div v-if="scope.row.goodsAmount">
                <div>￥{{scope.row.goodsAmount}}</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column width="150px" label="实付金额" prop="actualPrice">
            <template slot-scope="scope">
              <div v-if="scope.row.actualPrice">
                <div>￥{{scope.row.actualPrice}}</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column width="150px" label="实收金额" prop="enterpriseAmount">
            <template slot-scope="scope">
              <div v-if="scope.row.payType === 5">
                <div v-if="scope.row.actualPrice">
                  <div>￥{{scope.row.actualPrice}}</div>
                </div>
              </div>
              <div v-else>
                <div v-if="scope.row.enterpriseAmount">
                  <div>￥{{scope.row.enterpriseAmount}}</div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column width="200px" label="时间" align="center">
            <template slot-scope="scope">
              <div v-if="scope.row.createTime">生成：{{ scope.row.createTime }}</div>
              <div v-if="scope.row.payTime">付款：{{ scope.row.payTime }}</div>
              <div v-if="scope.row.deliveryTime">发货：{{ scope.row.deliveryTime }}</div>
              <div v-if="scope.row.receivedTime">收货：{{ scope.row.receivedTime }}</div>
              <div v-if="scope.row.completeTime">完成：{{ scope.row.completeTime }}</div>
              <div v-if="scope.row.cancelTime">取消：{{ scope.row.cancelTime }}</div>
            </template>
          </el-table-column>
          <el-table-column width="150px" label="订单状态" v-if="order.orderStatus == 100">
            <template slot-scope="scope">
              <template>
                {{ dict.orderStatus[scope.row.orderStatus] }}
              </template>
            </template>
          </el-table-column>
          <el-table-column width="120px" label="包裹数量" prop="packageNum">
          </el-table-column>
          <el-table-column min-width="240px" label="操作" fixed="right" align="right">
            <template slot-scope="scope">
              <el-button type="text" size="medium" @click="uploadProofPaymentImage(scope.row)"
                v-if="scope.row.orderStatus == 0 && scope.row.payType === 5">上传线下打款证明</el-button>
              <el-button type="text" size="medium" @click="showApplyDetail(scope.row)" v-if="scope.row.payType === 5">
                线下打款记录</el-button>
              <el-button type="text" size="medium" @click="showDetail(scope.row)">查看详情</el-button>
              <template v-if="!warehouseDeliverFlag">
                <el-button type="text" size="medium" v-if="scope.row.enterpriseDeliveryFlag == 1" @click="doOpenDeliver(scope.row)">发货</el-button>
              </template>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 列表分页 -->
      <div class="pagination">
        <el-pagination background 
          @size-change="handleSizeChange" 
          @current-change="handleCurrentChange"
          :current-page="searchListQuery.currentPage" 
          :page-sizes="[10, 20, 50, 100]" 
          :page-size="searchListQuery.size"
          layout="total, sizes, prev, pager, next, jumper" 
          :total="total">
        </el-pagination>
      </div>
    </div>

    <!-- 发货单管理dialog -->
    <el-dialog width="1200px" v-el-drag-dialog title="发货单管理" :visible.sync="orderDeliverVisible" :show-close="false">
      <order-send-manage :showFlag="orderDeliverVisible" :apartOrderId="selectApartOrderId" @callback="doCallbackOrderDeliver">
      </order-send-manage>
    </el-dialog>

    <!-- 上传线下打款证明 -->
    <el-dialog width="700px" title="上传线下打款证明" :visible.sync="proofPaymentImageVisible">
      <el-form ref="offlinePaymentApplyFormRef" :model="offlinePaymentApplyForm" label-position="right"
        label-width="100px" style='width: 500px; margin-left:50px;'>
        <el-form-item label="转账凭证:" prop="proofPaymentImage">
          <el-upload class="upload-demo" drag :show-file-list="false" action="/api/common/uploadFiles"
            accept="image/jpeg,image/gif,image/png,image/bmp" :before-upload="beforeUploadProofPaymentImage"
            name="files" :data="token" :on-success="handleUploadProofPaymentImageSuccess">
            <img v-if="offlinePaymentApplyForm.proofPaymentImage" :src="offlinePaymentApplyForm.proofPaymentImage"
              height="200px">
            <div v-else>
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              <div class="el-upload__tip" slot="tip">只能上传jpg/png文件且不超过2M，建议尺寸621x800</div>
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="proofPaymentImageVisible = false">取消</el-button>
        <el-button type="primary" @click="saveOfflinePaymentApply">确定</el-button>
      </div>
    </el-dialog>
  </div>

</template>

<script>
  import { pageProjectOrder, statProjectOrder } from '@/api/goods/order'
  import { downloadFile } from '@/api/common/common'
  import { getByEnterpriseId } from '@/api/user/enterprise'
  import { getToken } from '@/utils/auth'
  import { saveProjectOrderOfflinePaymentApply } from '@/api/finace/wholesaleOfflinePaymentApply'
  import elDragDialog from '@/directive/el-dragDialog'
  import orderSendManage from '@/views/goods/order/components/order-send-manage'
  
  export default {
    components: { orderSendManage },
    directives: {
      elDragDialog
    },
    data() {
      return {
        labels: {
          '0': '待付款(0)',
          '1': '待发货(0)',
          '20': '部分发货(0)',
          '2': '待收货(0)',
          '3': '已收货(0)',
          '4': '已完成(0)',
          '5': '已取消(0)',
          '100': '全部订单(0)'
        },
        sourceList: {
          '10': '企业订单',
          '20': '供应商订单',
          '30': '淘宝联盟订单',
          '40': '供货联盟订单'
        },
        multipleSelection: [],
        orderDeliverVisible: false,
        // 仓库发货flag
        warehouseDeliverFlag: false,
        total: 0,
        listLoading: true,
        searchListQuery: {},
        defaultQuery: {
          enterpriseId: this.getEnterpriseId(),
          orderType: 31,
          currentPage: 1,
          size: 10
        },
        order: {
          orderStatus: '1',
          timeCol: 'createTime',
          timeValue: [],
          textCol: 'orderNo',
          textValue: '',
          isNotice: false,
          apartOrderSource: '',
          isSupplyAllianceOrder: ''
        },
        dict: {
        },
        orderList: [],
        allChecked: false,
        // 选择订单id
        selectOrderId: '',
        selectApartOrderId: '',
        // 选中订单id集合
        selectOrderIds: [],
        // 选中批次id
        selectBatchId: '',
        // 生成批次提示表单
        hintForm: {
          failOrderNos: '',
          total: 0,
          successCount: 0,
          failCount: 0
        },
        token: '',
        proofPaymentImageVisible: false,
        offlinePaymentApplyForm: {
          enterpriseId: this.getEnterpriseId(),
          orderId: undefined,
          proofPaymentImage: undefined,
          applySource: 2
        }
      }
    },
    // 初始化页面
    created() {
      this.token = {
        accessToken: getToken()
      }
      getByEnterpriseId(this.getEnterpriseId()).then(response => {
        this.enterpriseConfig = response.data
        this.warehouseDeliverFlag = this.enterpriseConfig.warehouseAuthority === 1 && this.enterpriseConfig
          .warehouseDeliverFlag === 1
      })
      this.searchListQuery = {
        ...this.defaultQuery
      }
      this.init()
    },
    methods: {
      handleSelectionChange(val) {
        this.multipleSelection = val
        if (this.multipleSelection.length === this.orderList.length) {
          this.allChecked = true
        } else {
          this.allChecked = false
        }
      },
      // 更改当前页数
      handleCurrentChange(val) {
        this.searchListQuery.currentPage = val
        this.init()
      },
      // 更改当前页面大小
      handleSizeChange(val) {
        this.searchListQuery.size = val
        this.init()
      },
      setSearchListQuery() {
        // 搜索状态
        const currentPage = this.searchListQuery.currentPage
        const size = this.searchListQuery.size
        this.searchListQuery = {
          ...this.defaultQuery
        }
        this.searchListQuery.enterpriseId = this.getEnterpriseId()
        this.searchListQuery.currentPage = currentPage
        this.searchListQuery.page = currentPage
        this.searchListQuery.size = size
        switch (this.order.orderStatus * 1) {
          case 100:
            this.searchListQuery.orderStatus = ''
            break
          default:
            this.searchListQuery.orderStatus = this.order.orderStatus
        }
        this.searchListQuery.dateColumn = this.order.timeCol
        this.searchListQuery.startDate = (this.order.timeValue && this.order.timeValue.length > 0) ? this.order
          .timeValue[0] : ''
        this.searchListQuery.endDate = (this.order.timeValue && this.order.timeValue.length > 1) ? this.order.timeValue[
          1] : ''
        this.searchListQuery[this.order.textCol] = this.order.textValue
        this.searchListQuery.apartOrderSource = this.order.apartOrderSource
        this.searchListQuery.crossBorderOrderType = 1
        this.searchListQuery.isSupplyAllianceOrder = this.order.isSupplyAllianceOrder
      },
      init() {
        this.listLoading = true
        this.setSearchListQuery()
        statProjectOrder({
          enterpriseId: this.getEnterpriseId(),
          orderType: this.defaultQuery.orderType,
          crossBorderOrderType: this.searchListQuery.crossBorderOrderType
        }).then(response => {
          if (response.isError) return
          this.labels[0] = '待付款(' + response.data[0] + ')'
          this.labels[1] = '待发货(' + response.data[1] + ')'
          this.labels[20] = '部分发货(' + response.data[20] + ')'
          this.labels[2] = '待收货(' + response.data[2] + ')'
          this.labels[3] = '已收货(' + response.data[3] + ')'
          this.labels[4] = '已完成(' + response.data[4] + ')'
          this.labels[5] = '已取消(' + (response.data[-1] + response.data[-2]) + ')'
          this.labels[100] = '全部订单(' + response.data[100] + ')'
        })
        pageProjectOrder(this.searchListQuery).then(response => {
          this.listLoading = false
          if (response.isError) return
          this.total = response.data.total
          this.orderList = response.data.records
          this.dict = response.data.dict
        })
      },
      orderStatusClick() {
        this.searchListQuery.currentPage = 1
        this.init()
      },
      showDetail(row) {
        this.$router.push({
          path: '/order/order/detail/index',
          query: {
            orderId: row.orderId
          }
        })
      },
      // 批量生成发货单事件
      doBatchGenerateSend() {
        if (this.multipleSelection.length <= 0) {
          this.$message({ message: '请勾选数据', type: 'warning' })
          return
        }
        const params = {
          enterpriseId: this.getEnterpriseId(),
          systemRoleType: this.getSystemRoleType(),
          orderIds: this.multipleSelection.map(item => item.orderId)
        }
        this.$bus.$emit('asyncHandle', '300003', params, () => {
          this.init()
        })
      },
      // 打开发货dialog事件
      doOpenDeliver(row) {
        this.selectApartOrderId = row.apartOrderId
        this.orderDeliverVisible = true
      },
      // 订单发货回调事件
      doCallbackOrderDeliver(callbackFlag) {
        if (callbackFlag) {
          this.init()
        }
        this.orderDeliverVisible = false
      },
      exportOrder() {
        if (this.multipleSelection.length > 0) {
          const orderIds = this.multipleSelection.map(item => item.orderId)
          downloadFile('/goods/projectOrder/exportOrder', {
            enterpriseId: this.getEnterpriseId(),
            orderIds: orderIds.join(',')
          }, '批发订单.xlsx')
        } else {
          const params = {
            enterpriseId: this.getEnterpriseId(),
            orderType: 31
          }
          this.setSearchListQuery()
          Object.assign(params, this.searchListQuery)
          downloadFile('/goods/projectOrder/exportOrder', params, '批发订单.xlsx')
        }
      },
      handleSearch() {
        this.searchListQuery.currentPage = 1
        this.init()
      },
      resetSearch() {
        this.searchListQuery = {
          ...this.defaultQuery
        }
        this.order = {
          timeCol: 'createTime',
          timeValue: [],
          textCol: 'orderNo',
          textValue: ''
        }
        this.init()
      },
      selectAll() {
        if (this.multipleSelection.length === 0 || this.multipleSelection.length < this.orderList.length) {
          this.orderList.forEach(item => {
            this.$refs.multipleTable.toggleRowSelection(item, true)
          })
        } else {
          this.$refs.multipleTable.clearSelection()
        }
      },
      showApplyDetail(row) {
        const routeUrl = this.$router.resolve({
          path: '/finace/wholesale-offline-payment-apply/index',
          query: {
            orderId: row.orderId
          }
        })
        window.open(routeUrl.href, '_blank')
      },
      beforeUploadProofPaymentImage(file) {
        const isJPG = file.type === 'image/jpeg'
        const isGIF = file.type === 'image/gif'
        const isPNG = file.type === 'image/png'
        const isBMP = file.type === 'image/bmp'

        if (!isJPG && !isGIF && !isPNG && !isBMP) {
          this.$message.error('上传图片必须是JPG/GIF/PNG/BMP 格式!')
        }
        return (isJPG || isBMP || isGIF || isPNG)
      },
      handleUploadProofPaymentImageSuccess(res, file) {
        if (res.code === 101) {
          this.offlinePaymentApplyForm.proofPaymentImage = res.data[0]
        }
      },
      // 上传付款凭证图片
      uploadProofPaymentImage(row) {
        if (row.isCanApplyOfflinePayment === 1) {
          this.proofPaymentImageVisible = true
          this.offlinePaymentApplyForm.orderId = row.orderId
        } else {
          this.msgError('存在待审核的申请!')
          return
        }
      },
      // 查看售后事件
      doLinkAfter(row) {
        const routeData = this.$router.resolve({
          path: '/order/after-sale/list',
          query: { orderNo: row.orderNo }
        })
        window.open(routeData.href, '_blank')
      },
      // 保存上传线下打款证明数据
      saveOfflinePaymentApply() {
        var that = this
        if (!that.offlinePaymentApplyForm.orderId) {
          that.msgError('没有订单id，无法保存!')
          return
        }
        if (!that.offlinePaymentApplyForm.proofPaymentImage) {
          that.msgError('请上传转账凭证图片!')
          return
        }
        that.$confirm('确定要上传转账凭证吗？', '温馨提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          saveProjectOrderOfflinePaymentApply(that.offlinePaymentApplyForm).then(response => {
            if (response.isError) return
            that.proofPaymentImageVisible = false
            that.msgSuccess(response.msg)
            that.init()
            that.offlinePaymentApplyForm.orderId = undefined
            that.offlinePaymentApplyForm.proofPaymentImage = undefined
          })
        })
      }
    }
  }
</script>

<style lang="less" scoped>
  .goods-title {
    color: #155bd4;
    line-height: 1.2;
  }
  .cus-select {
    width: 160px;

    /deep/ .el-input {
      width: 160px;
    }
  }
</style>
